package com.ljd.controller;

import com.google.gson.Gson;
import com.ljd.entity.UcenterMember;
import com.ljd.service.UcenterMemberService;
import com.ljd.util.JwtUtils;
import com.ljd.utils.ConstantPropertiesUtil;
import com.ljd.utils.HttpClientUtils;
import com.why.handler.GuliException;
import org.aspectj.apache.bcel.classfile.Code;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;

@Controller //不需要响应体
@RequestMapping("/api/ucenter/wx")
//@CrossOrigin
public class WxApiController {

    @Autowired
    UcenterMemberService memberService;
    @GetMapping("/callback")
    public String callback(@RequestParam String code,@RequestParam String state){

        try {
            //1 获取code值，临时票据，类似于验证码
            //2 拿着code请求 微信固定的地址，得到两个值 accsess_token 和 openid
            String baseAccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token" +
                    "?appid=%s" +
                    "&secret=%s" +
                    "&code=%s" +
                    "&grant_type=authorization_code";
            //拼接三个参数 ：id  秘钥 和 code值
            String accessTokenUrl = String.format(
                    baseAccessTokenUrl,
                     ConstantPropertiesUtil.WX_OPEN_APP_ID,
                    ConstantPropertiesUtil.WX_OPEN_APP_SECRET,
                    code
            );
            // 请求这个地址，返回access_token,openid
            // 使用httpclient发送请求，得到返回结果（不需要游览器也能拿到请求数据) （这里使用httpclient原因是在扫码以后没有用游览器请求地址用他发送两次请求得到微信用户信息）
            String accessTokenInfo = HttpClientUtils.get(accessTokenUrl);
            System.out.println(accessTokenInfo);
            // 从accessTokenInfo获取access_token,openid
            // {"access_token":"52_CIXqW8t5WDsRO2rOoNnOhf__lUQbhvgQV3ne9IW9_qQ_HFyh9-PemFs2hOlFWtygpBn3L-EfJCRj9zxqr-IwIccs7YEKrrarD_K59VLtg58",
            // "expires_in":7200,"refresh_token":"52_wG0qoz5a1TO55t3vJQZikTFZuRVxECxpIrECFT21fujKa5JZqgAXcNh9AIJXqqHinmglMcDsd06_PLlx99uVfjaCFV50hCX6dRA0B8LfRoQ",
            // "openid":"o3_SC598S5aZ6-kWtZjvtkCEPlFY","scope":"snsapi_login","unionid":"oWgGz1MCswtF3kvX2mmX8V46udNM"}
            // accessTokenInfo返回的是一个json字符串,通过gson将字符串转为map，然后取值
            Gson gson = new Gson();
            HashMap mapAccessToken = gson.fromJson(accessTokenInfo, HashMap.class);
            String access_token =(String) mapAccessToken.get("access_token");
            String openid = (String) mapAccessToken.get("openid");
            // 把扫面人信息添加到数据库
            //判断数据库表是否有改扫描人信息

            UcenterMember member = memberService.getByOpenId(openid);

            if(member==null){
                // 拿着得到的access_token,openid 再去请求微信固定地址，获取扫描人信息
                String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                        "?access_token=%s" +
                        "&openid=%s";
                // 拼接两个参数
                String userInfoUrl = String.format(
                        baseUserInfoUrl,
                        access_token,
                        openid
                );
                // 发送请求
                String userInfo = HttpClientUtils.get(userInfoUrl);
                System.out.println(userInfo);
                //{"openid":"o3_SC598S5aZ6-kWtZjvtkCEPlFY","nickname":"偏一月","sex":0,"language":"","city":"","province":"","country":"",
                // "headimgurl":"https:\/\/thirdwx.qlogo.cn\/mmopen\/vi_32\/6weggPh5FRWqeiadslnVotsZArHDdua1hia5oCXhpvxRqEZLujpHgibvku5lE65gytqHia0U6q70MFRNvIZlbO98QQ\/132",
                // "privilege":[],"unionid":"oWgGz1MCswtF3kvX2mmX8V46udNM"}
                HashMap mapUserInfo = gson.fromJson(userInfo, HashMap.class);
                String nickname = (String) mapUserInfo.get("nickname");
                String headimgurl = (String) mapUserInfo.get("headimgurl");

                member = new UcenterMember();
                member.setOpenid(openid);
                member.setAvatar(headimgurl);
                member.setNickname(nickname);
                memberService.save(member);
            }
            String jwtToken = JwtUtils.getJwtToken(member.getId(), member.getNickname());



            return "redirect:http://localhost:3000?token="+jwtToken;
        } catch (Exception e) {
            throw new GuliException(20001,"微信登陆失败");
        }
    }
    // 生成微信扫描二维码
    @GetMapping("login")
    public String getWxCode(){

        // 微信开放平台授权baseUrl  %s相当于?代表占位符(s代表字符串)
        String baseUrl = "https://open.weixin.qq.com/connect/qrconnect" +
                "?appid=%s" +
                "&redirect_uri=%s" +
                "&response_type=code" +
                "&scope=snsapi_login" +
                "&state=%s" +
                "#wechat_redirect";


        //对redirect_url进行URLEncoder编码
        String redirectUrl = ConstantPropertiesUtil.WX_OPEN_REDIRECT_URL;
        try {
            redirectUrl = URLEncoder.encode(redirectUrl, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        //设置%s里面值
        String url = String.format(
                baseUrl,
                ConstantPropertiesUtil.WX_OPEN_APP_ID,
                redirectUrl,
                "dong"
        );
        return "redirect:"+url;
    }
}
